<template>
  <div class="container">
    <Breadcrumb :items="['menu.list', 'menu.wms.warehouse.list']" />
    <a-card class="general-card" :title="$t('menu.wms.warehouse.list')">

      <!-- 头部区域 -->
      <div class="header">
        <!-- 搜索栏 -->
        <div v-if="showQuery" class="header-query">
          <a-form ref="queryRef" :model="queryParams" layout="inline">
            
            <a-form-item field="warehouseName" hide-label>
              <a-input
                  v-model="queryParams.warehouseName"
                  placeholder="输入仓库名搜索"
                  allow-clear
                  style="width: 150px"
                  @press-enter="handleQuery"
              />
            </a-form-item>


            <a-form-item hide-label>
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  <template #icon><icon-search /></template>查询
                </a-button>
                <a-button @click="resetQuery">
                  <template #icon><icon-refresh /></template>重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <!-- 操作栏 -->
        <div class="header-operation">
          <a-row>
            <a-col :span="16">
              <a-space>
                <a-button v-permission="['system:warehouse:add']" type="primary" @click="toAdd">
                  <template #icon><icon-plus/></template>新增
                </a-button>

                <a-button
                    v-permission="['system:warehouse:update']"
                    type="primary"
                    status="success"
                    :disabled="single"
                    :title="single ? '请选择一条要修改的数据' : ''"
                    @click="toUpdate(checkedIds[0])"
                >
                  <template #icon><icon-edit /></template>修改
                </a-button>
                <a-button
                    v-permission="['system:warehouse:delete']"
                    type="primary"
                    status="danger"
                    :disabled="multiple"
                    :title="multiple ? '请选择要删除的数据' : ''"
                    @click="handleBatchDelete"
                >
                  <template #icon><icon-delete /></template>删除
                </a-button>
                <a-button
                    v-permission="['system:warehouse:export']"
                    :loading="exportLoading"
                    type="primary"
                    status="warning"
                    @click="handleExport"
                >
                  <template #icon><icon-download /></template>导出
                </a-button>
              </a-space>
            </a-col>
            <a-col :span="12">
              <right-toolbar v-model:show-query="showQuery" @refresh="fetchData"/>
            </a-col>
          </a-row>
        </div>
      </div>


      <a-table
          row-key="id"
          :data="warehouseList"
          :loading="loading"
          :pagination="{
              showTotal: true,
              showPageSize: true,
              total: total,
              current: queryParams.page,
            }"
          :bordered="false"
          :size="size"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
          @selection-change="handleSelectionChange"
          :row-selection="{
              type: 'checkbox',
              showCheckedAll: true,
              onlyCurrent: false,
            }"
      >

        <template #columns>
          <a-table-column title="ID" data-index="id" :width="85" />
          <a-table-column title="仓库名" :width="150">
            <template #cell="{ record }">
              <a-link @click="toDetail(record.id)">{{
                  record.warehouseName
                }}</a-link>
            </template>
          </a-table-column>

          <a-table-column title="供应商名称" :width="130">
            <template #cell="{ record }">
              {{ record.supplierName }}
            </template>
          </a-table-column>



          <a-table-column title="仓库类型" :width="100">
            <template #cell="{ record }">
              <span v-if="record.warehouseType === 1">自营仓</span>
              <span v-else-if="record.warehouseType === 2">第三方</span>
              <span v-else>未知</span>
            </template>
          </a-table-column>


          <a-table-column title="仓库地址" :width="130">
            <template #cell="{ record }">
              {{ record.warehouseAddress }}
            </template>
          </a-table-column>

          <a-table-column title="仓管姓名" :width="130">
            <template #cell="{ record }">
              {{ record.warehouseAdminName }}
            </template>
          </a-table-column>

          <a-table-column title="仓管电话" :width="130">
            <template #cell="{ record }">
              {{ record.warehouseAdminPhone }}
            </template>
          </a-table-column>


          <a-table-column
              title="操作"
              align="center"
              fixed="right"
              :width="50"
          >
            <template #cell="{ record }">
              <a-button
                  v-permission="['system:warehouse:update']"
                  type="text"
                  size="small"
                  title="修改"
                  @click="toUpdate(record.id)"
              >
                <template #icon><icon-edit /></template>
              </a-button>

              <a-popconfirm
                  content="确定删除吗？"
                  type="warning"
                  @ok="handleDelete([record.id])"
              >
                <a-button
                    v-permission="['system:warehouse:delete']"
                    type="text"
                    size="small"
                    title="删除"
                    :disabled="record.disabled"
                >
                  <template #icon><icon-delete /></template>
                </a-button>
              </a-popconfirm>

            </template>
          </a-table-column>
        </template>


      </a-table>
    </a-card>


    <!-- 表单区域 -->
    <a-modal
        :title="title"
        :visible="visible"
        :width="580"
        :mask-closable="false"
        unmount-on-close
        render-to-body
        @ok="handleOk"
        @cancel="handleCancel"
    >
      <a-form
          ref="formRef"
          :model="warehouseAddForm"
          :rules="rules"
          :label-col-style="{ width: '84px' }"
          size="large"
          layout="inline"
      >
        <a-form-item label="仓库名" field="warehouseName">
          <a-input
              v-model="warehouseAddForm.warehouseName"
              placeholder="请输入仓库名"
              style="width: 162px"
          />
        </a-form-item>
        <a-form-item label="供应商名" field="supplierName">
          <a-input
              v-model="warehouseAddForm.supplierName"
              placeholder="请输入供应商名称"
              style="width: 162px"
          />
        </a-form-item>
        <a-form-item label="仓库地址" field="warehouseAddress">
          <a-input
              v-model="warehouseAddForm.warehouseAddress"
              placeholder="请输入仓库地址"
              style="width: 162px"
          />
        </a-form-item>
        <a-form-item label="仓管姓名" field="warehouseAdminName">
          <a-input
              v-model="warehouseAddForm.warehouseAdminName"
              placeholder="请输入仓管姓名"
              style="width: 162px"
          />
        </a-form-item>
        <a-form-item label="仓管手机" field="warehouseAdminPhone">
          <a-input
              v-model="warehouseAddForm.warehouseAdminPhone"
              placeholder="请输入仓管手机"
              style="width: 162px"
          />
        </a-form-item>
        <a-form-item label="仓库类型" field="warehouseType">
          <a-radio-group v-model="warehouseAddForm.warehouseType">
            <a-radio :value="1">自营仓</a-radio>
            <a-radio :value="2">第三方</a-radio>
            <a-radio :value="0" disabled>未知</a-radio>
          </a-radio-group>
        </a-form-item>



      </a-form>
    </a-modal>

    <a-drawer
        title="仓库详情"
        :visible="detailVisible"
        :width="700"
        :footer="false"
        unmount-on-close
        render-to-body
        @cancel="handleDetailCancel"
    >
      <a-descriptions :column="2" bordered size="large">
        <a-descriptions-item label="仓库名">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.warehouseName }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="供应商名">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.supplierName }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="仓库类型">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>
              <a-tag v-if="warehouse.warehouseType === 1" color="green">自营仓</a-tag>
              <a-tag v-else-if="warehouse.warehouseType === 2" color="green">第三方</a-tag>
              <a-tag v-else color="red">未知</a-tag>
            </span>
        </a-descriptions-item>

        <a-descriptions-item label="仓库地址">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.warehouseAddress || '无' }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="仓管姓名">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.warehouseAdminName || '无' }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="仓管手机">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.warehouseAdminPhone }}</span>
        </a-descriptions-item>

        
        <a-descriptions-item label="创建者">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.createdBy }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="创建时间">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.createdAt }}</span>
        </a-descriptions-item>


        <a-descriptions-item label="更新者">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.updatedBy }}</span>
        </a-descriptions-item>

        <a-descriptions-item label="更新时间">
          <a-skeleton v-if="detailLoading" :animation="true">
            <a-skeleton-line :rows="1" />
          </a-skeleton>
          <span v-else>{{ warehouse.updatedAt }}</span>
        </a-descriptions-item>

  
      </a-descriptions>
    </a-drawer>

  </div>



</template>

<script lang="ts" setup>
  import {getCurrentInstance, reactive, ref, toRefs} from 'vue';
  import {useI18n} from 'vue-i18n';
  import useLoading from '@/hooks/loading';
  import {PolicyRecord} from '@/api/list';
  import {
    addWarehouse,
    getWarehouse,
    updateWarehouse,
    deleteWarehouse,
    WarehouseSaveCommand,
    WarehouseParam,
    WarehouseResponse,
    pageWarehouse
  } from "@/api/wms/warehouse";
  import checkPermission from '@/utils/check-permission';
  import {listRoleDict} from "@/api/system/role";
  import {DictResponseState} from "@/store/modules/dict/types";
  import {AxiosResponse} from "axios";
  import {HttpResponse} from "@/api/interceptor";

  const showQuery = ref(true);

  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const { proxy } = getCurrentInstance() as any;
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const renderData = ref<PolicyRecord[]>([]);

  const size = ref<SizeProps>('medium');
  const checkedIds = ref<Array<number>>([]);
  const title = ref('');
  const single = ref(true);
  const multiple = ref(true);

  const data = reactive({
    queryParams: {
      warehouseName: undefined,
      status: 1,
      createdAt: undefined,
      page: 1,
      size: 10,
      sort: ['createdAt,desc'],
    },
    warehouseAddForm: {} as WarehouseSaveCommand,
    rules: {
      warehouseName: [{ required: true, message: '请输入管理员仓库名' }]
    },

  });
  const { queryParams,warehouseAddForm,rules } = toRefs(data);

  const warehouseList = ref<WarehouseResponse[]>([]);
  const total = ref(0);

  const warehouse = ref<WarehouseResponse>({
    id: undefined,
    supplierName: '',
    warehouseName: '',
    warehouseType: 0,
    warehouseAddress: '',
    warehouseAdminName: '',
    warehouseAdminPhone: '',
    createdBy: '',
    updatedBy: '',
    createdAt: '',
    updatedAt: '',
  });

  const fetchData = (params: WarehouseParam = {...queryParams.value}) => {
    setLoading(true);
    pageWarehouse(params).then(res => {
      warehouseList.value = res.data.list;
      total.value = Number(res.data.total);
    }).finally(() => {
      setLoading(false);
    });

  };

  fetchData();
  const reset = () => {
    warehouseAddForm.value = {
      id: undefined,
      supplierName: '',
      warehouseName: '',
      warehouseType: 0,
      warehouseAddress: '',
      warehouseAdminName: '',
      warehouseAdminPhone: ''
    };
    proxy.$refs.formRef?.reserFields();
  };

  const visible = ref(false);
  const toAdd = () => {
    reset();
    getRoleOptions();
    title.value = '新增仓库';
    visible.value = true;
  };

  const roleLoading = ref(false);
  const roleOptions = ref<DictResponseState[]>([]);

  const getRoleOptions = () => {
    roleLoading.value = true;
    listRoleDict({})
        .then((res) => {
          roleOptions.value = res.data;
        })
        .finally(() => {
          roleLoading.value = false;
        });
  };

  const toUpdate = (id: number) => {
    reset();
    getRoleOptions();
    getWarehouse(id).then((res) => {
      warehouseAddForm.value = res.data as unknown as WarehouseSaveCommand;
      title.value = '修改仓库';
      visible.value = true;
    });
  };

  const handleQuery = () => {
    console.log("handleQuery", queryParams);
    fetchData();
  };

  const resetQuery = () => {
    proxy.$refs.queryRef.resetFields();
    handleQuery();
  };

  const handlePageChange = (current: number) => {
    queryParams.value.page = current;
    fetchData();
  };

  const handlePageSizeChange = (pageSize: number) => {
    queryParams.value.size = pageSize;
    fetchData();
  };

  const handleSelectionChange = (rowKeys: Array<any>) => {
    checkedIds.value = rowKeys;
    single.value = rowKeys.length !== 1;
    multiple.value = !rowKeys.length;
  };


  const handleCancel = () => {
    visible.value = false;
    warehouseRoleVisible.value =false;
    proxy.$refs.formRef?.resetFields();
    proxy.$refs.userRoleFormRef?.resetFields();
  };

  const handleOk = () => {
    proxy.$refs.formRef.validate((valid: any) => {
      if (!valid) {
        if (warehouseAddForm.value.id !== undefined) {
          updateWarehouse(warehouseAddForm.value).then((res:any) => {
            handleCancel();
            fetchData();
            proxy.$message.success(res.message);
          });
        } else {
          addWarehouse(warehouseAddForm.value).then((res:any) => {
            handleCancel();
            fetchData();
            proxy.$message.success(res.message);
          });
        }
      }
    });
  };

  const handleDelete = (ids: Array<number>) => {
    deleteWarehouse(ids).then((res:any) => {
      proxy.$message.success(res.message);
      fetchData();
    });
  };

  const warehouseRoleVisible = ref(false);
  const toUpdateRole = (id: number) => {
    reset();
    getRoleOptions();
    getWarehouse(id).then((res) => {
      warehouseAddForm.value = res.data as unknown as WarehouseSaveCommand;
      warehouseRoleVisible.value = true;
    });
  };

  const detailLoading = ref(false);
  const detailVisible = ref(false);
  const toDetail = async (id: number) => {
    if (detailLoading.value) return;
    detailLoading.value = true;
    detailVisible.value = true;
    getWarehouse(id)
        .then((res) => {
          warehouse.value = res.data;
        })
        .finally(() => {
          detailLoading.value = false;
        });
  };

  const handleDetailCancel = () => {
    detailVisible.value = false;
  };

  const handleBatchDelete = () => {
    if(checkedIds.value.length === 0) {
      proxy.$message.info('没有选中数据');
    }else {
      proxy.$modal.warning({
        title: '警告',
        titleAlign: "start",
        content: '确定删除吗？',
        hideCancel: false,
        onOk: () => {
          handleDelete(checkedIds.value);
        }
      });
    }
  }

  const exportLoading = ref(false);
  const handleExport = () => {
    if(exportLoading.value) return;

    exportLoading.value = true;
    proxy
        .download('/warehouse/system/warehouse/export', { ...queryParams.value }, '仓库数据')
        .finally(() => {
          exportLoading.value = false;
        });

  }


</script>

<script lang="ts">
export default {
  name: 'SearchTable',
};
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.header {
  padding-bottom: 10px;
}
</style>
